package com.epam.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.epam.entity.User;
import com.epam.entity.User.Role;
import com.epam.util.ConfigurationManager;

/**
 * Servlet Filter implementation class AccessFilter
 */
public class AccessFilter implements Filter {
	
	private static final Logger LOG = Logger.getLogger(AccessFilter.class);

	public AccessFilter() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	
		HttpServletRequest request =  (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();
		
		Role role =  (Role) session.getAttribute("role");

		if (checkURI(request)) {
			if (role.equals(User.Role.ADMIN)) {
				LOG.info("role check: successful");
				chain.doFilter(request, response);
			} else {
				LOG.info("role check: fail");
				response.sendRedirect(ConfigurationManager.getConfig(ConfigurationManager.LOGIN_PAGE));
			}
		} else {
			if (role.equals(User.Role.USER) || role.equals(User.Role.ADMIN)) {
				LOG.info("role check: successful");
				chain.doFilter(request, response);
			} else {
				LOG.info("role check: fail");
				response.sendRedirect(ConfigurationManager.getConfig(ConfigurationManager.LOGIN_PAGE));
			}
		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

	private boolean checkURI(HttpServletRequest request) {
		
		String requestURI = request.getRequestURI();
		String adminPage = ConfigurationManager
				.getConfig(ConfigurationManager.ADMIN_PAGE);
		String userManager = ConfigurationManager
				.getConfig(ConfigurationManager.USER_MANAGER);
		String tourManager = ConfigurationManager
				.getConfig(ConfigurationManager.TOUR_MANAGER);
		String hotelManager = ConfigurationManager
				.getConfig(ConfigurationManager.HOTEL_MANAGER);
		
		if (requestURI.contains(adminPage) ||
				requestURI.contains(userManager) ||
				requestURI.contains(tourManager) ||
				requestURI.contains(hotelManager)) {
			
			return true;
		} else {
			return false;
		}
	}
}
